package cn.shop.dys.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.CycleInterpolator;
import android.widget.AdapterView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/*import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechConfig;
import com.iflytek.speech.SpeechError;
import com.iflytek.ui.RecognizerDialog;
import com.iflytek.ui.RecognizerDialogListener;*/
import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechConfig;
import com.iflytek.speech.SpeechError;
import com.iflytek.ui.RecognizerDialog;
import com.iflytek.ui.RecognizerDialogListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.squareup.otto.Subscribe;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import cn.shop.dys.R;
import cn.shop.dys.adapter.LeftMenuItemAdapter;
import cn.shop.dys.adapter.SearchAdapter;
import cn.shop.dys.adapter.SearchHistoryAdapter;
import cn.shop.dys.bean.CartProInDB;
import cn.shop.dys.bean.LeftMenuItem;
import cn.shop.dys.bean.ProductInfo;
import cn.shop.dys.bean.SearchHistoryInfo;
import cn.shop.dys.bean.SearchInfo;
import cn.shop.dys.bean.UserInfo;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.dys.constant.SPConstant;
import cn.shop.dys.dao.CartDao;
import cn.shop.dys.db.dbinfo.SearchHistoryDBInfo;
import cn.shop.dys.fragment.BaseFragment;
import cn.shop.dys.fragment.CartFragment;
import cn.shop.dys.fragment.FourFragment;
import cn.shop.dys.fragment.HomeFragment;
import cn.shop.dys.fragment.CategoryFragment;
import cn.shop.dys.util.BusFactory;
import cn.shop.dys.util.SPUtil;
import cn.shop.dys.util.SearchHistoryInfoDBUtil;
import cn.shop.dys.util.UserInfoDBUtil;
import cn.shop.dys.widget.ChangeColorIconWithText;
import cn.shop.dys.widget.DragLayout;
import cn.shop.dys.widget.FlowLayout;
import cn.shop.dys.widget.MyCircleImageView;
import cn.shop.dys.widget.RollMenuView;
import cn.shop.lib_common.Cheeses;
import cn.shop.lib_common.CommonUtil;/**
 * 主界面逻辑数据处理
 * Created by sunjian on 2016/4/18.
 */
public class MainActivity2 extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener, ViewPager.OnPageChangeListener {
    /* @ViewInject(R.id.view_main)
         private MainContenLinearLayout mViewMain;*/
    @ViewInject(R.id.iv_main_icon)
    private MyCircleImageView mMainIcon;
    /* @ViewInject(R.id.msm_main)
     private MySlidingMenu mMySlidingMenu;*/
    @ViewInject(R.id.msm_main)
    private DragLayout mMySlidingMenu;
    @ViewInject(R.id.vp_main)
    private ViewPager mViewPager;
    @ViewInject(R.id.iv_head_left)
    private MyCircleImageView mImgLeftHead;
    @ViewInject(R.id.tv_main_title)
    private TextView mMainTitle;
    @ViewInject(R.id.tv_account_name)
    private TextView mAccountName;
    @ViewInject(R.id.left_lv)
    private ListView mLeftMenuListView;
    /* @ViewInject(R.id.iv_main_search)
     private ImageView mSearchImg;*/
    // private ArrayAdapter<LeftMenuItem> mLeftAdapter;
    private List<BaseFragment> mFragments = new ArrayList<>();
    private int scrollIndex;
    @ViewInject(R.id.tb_search)
    private Toolbar mToolbar;
    @ViewInject(R.id.ll_search_empty)
    private LinearLayout mSearchEmpty;
    @ViewInject(R.id.lv_search_list)
    private ListView mSearchList;
    /*@ViewInject(R.id.main_index)
    private MainContenLinearLayout mainViewIndex;*/
    @ViewInject(R.id.ll_showMsg)
    private View mLLShowMsg;
    @ViewInject(R.id.rl_searchMsg)
    private View mRLSearchMsg;
    private SearchView mSearchView;
    private SearchAdapter mAdapter;
    private MenuItem settingsItem;
    private boolean isVoice;
    private LeftMenuItemAdapter mLeftMenuItemAdapter;
    private List<LeftMenuItem> mLeftMenuItems = new ArrayList<>();
    private boolean isLogin;
    private UserInfo mUserInfo;
    private PopupWindow mPopupWindow;
    private MenuItem mSearch;
    @ViewInject(R.id.fl_hot_search)
    private FlowLayout mHotSearch;
    @ViewInject(R.id.lv_search_history_list)
    private ListView mSearchHistoryList;
    private List<SearchHistoryInfo> mSearchHistoryInfos = new ArrayList<>();
    private SearchHistoryAdapter mSearchHistoryAdapter;
    private List<SearchInfo> mSearchInos = new ArrayList<>();
    private HttpUtils mHttpUtils;
    private Gson mGson;
    private LayoutInflater mInflater;
    private boolean mIsBrand;
    private boolean mIsCart;
    private WindowManager mWm;
   private RecognizerDialog rd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        SearchHistoryInfoDBUtil.initDB(this, SearchHistoryDBInfo.DB_NAME);
        ViewUtils.inject(this);
        BusFactory.getBus().register(this);
        mHttpUtils = new HttpUtils();
        mGson = new Gson();
        mInflater = LayoutInflater.from(this);
      rd = new RecognizerDialog(this ,"appid=50e1b967");
        initToolbar();
        initHead();
        initSearchData();
        init();
        // TODO: 2016/4/23  创建购物车数据库 转移到splash
        initDB();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int mainIndex = intent.getIntExtra("mainIndex", -1);
        if(mainIndex>0){
            resetOtherTabs();
            mTabIndicators.get(mainIndex).setIconAlpha(1.0f);
            mViewPager.setCurrentItem(mainIndex,false);
        }else {
            resetOtherTabs();
            mTabIndicators.get(0).setIconAlpha(1.0f);
            mViewPager.setCurrentItem(0,false);
        }
    }

    /**
     * 购物车数据库初始化
     * 作者：张哲
     */
    private void initDB() {
        CartDao.init(this, "cart_data");

    }

    /**
     * 搜索数据初始化
     * 作者:孙建
     * created at 2016/4/20 22:50
     */
    private void initSearchData() {
        //初始化搜索历史数据
        // initHistoryData();
        //初始化热搜数据
        initHotSearchData();
    }

    /**
     * 需要的搜索信息
     * 作者:孙建
     * created at 2016/4/21 16:48
     */
    private void initNeedSearchInfo(SearchInfo searchInfo) {
        final String key = searchInfo.getKeyword();
        //  Log.d("test",key);
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        //http://localhost:8080/market/search?page=0&pageNum=10&orderby=saleDown&keyword=奶粉
        params.addQueryStringParameter("page", searchInfo.getPage() + "");
        params.addQueryStringParameter("pageNum", searchInfo.getPageNum() + "");
        params.addQueryStringParameter("keyword", searchInfo.getKeyword());
        params.addQueryStringParameter("orderby", searchInfo.getOrderby());
        mHttpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST_SEARCH, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if (response.equals("search")) {
                                    String productList = jsonObject.getString("productList");
                                    ArrayList<ProductInfo> mProductInfos = mGson.fromJson(productList, new TypeToken<List<ProductInfo>>() {
                                    }.getType());
                                    //       Log.d("test",mProductInfos.toString());
                                    if (mProductInfos.size() == 0 || mProductInfos == null) {
                                        Log.d("test", "没搜索到");
                                        Intent intent = new Intent(MainActivity2.this, SearchResultActivity.class);
                                        startActivity(intent);
                                    } else {
                                        SearchHistoryInfoDBUtil.saveSearchHistoryInfo(new SearchHistoryInfo(key));
                                        Log.d("test", key + "yyyyyyyyyyyyyyyyyyy");
                                        Intent intent=new Intent(MainActivity2.this,ProductListShowActivity.class);
                                        Bundle bundle=new Bundle();
                                        bundle.putString("key","search");
                                        bundle.putString("keyword",key);
                                        intent.putExtras(bundle);
                                        startActivity(intent);
                                    }
                                    /*Intent intent=new Intent(MainActivity2.this,SearchResultActivity.class);
                                    intent.putParcelableArrayListExtra("ProductInfos",mProductInfos);
                                    startActivity(intent);*/
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            MenuItemCompat.collapseActionView(mSearch);
                        } else {
                            CommonUtil.showToast(MainActivity2.this, "请求失败:错误码为" + statusCode);
                        }

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(MainActivity2.this, "网络未连接" + msg);
                    }

                });
    }

    /**
     * 初始化历史搜索数据
     * 作者:孙建
     * created at 2016/4/21 16:53
     */
    private void initHistoryData() {
        setSearchHistoryInfoAdapter();
    }

    /**
     * 搜索历史适配器
     * 作者:孙建
     * created at 2016/4/21 16:54
     */
    private void setSearchHistoryInfoAdapter() {
        List<SearchHistoryInfo> infos = SearchHistoryInfoDBUtil.queryAllSearchHistoryInfo();
        if (infos == null) return;
        mSearchHistoryInfos.clear();
        mSearchHistoryInfos.addAll(infos);
        if (mSearchHistoryAdapter == null) {
            mSearchHistoryAdapter = new SearchHistoryAdapter(mSearchHistoryInfos, this);
            mSearchHistoryList.setAdapter(mSearchHistoryAdapter);
            mSearchHistoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent=new Intent(MainActivity2.this,ProductListShowActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putString("key","search");
                    bundle.putString("keyword",mSearchHistoryInfos.get(position).getSearch_content());
                    intent.putExtras(bundle);
                    startActivity(intent);

                }
            });
        } else {
            mSearchHistoryAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 热搜数据初始化
     * 作者:孙建
     * created at 2016/4/21 16:54
     */
    private void initHotSearchData() {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        mHttpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST_SEARCH_RECOMMEND, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if (response.equals("searchrecommend")) {
                                    String searchKeywords = jsonObject.getString("searchKeywords");
                                    List<String> keywords = mGson.fromJson(searchKeywords,
                                            new TypeToken<List<String>>() {
                                            }.getType());
                                    if (keywords == null || keywords.size() == 0) {
                                        CommonUtil.showToast(MainActivity2.this, "推荐商品被偷了");
                                    } else {
                                        for (String keyword : keywords) {
                                            TextView tv = (TextView) mInflater.inflate(R.layout.view_text_view,
                                                    mHotSearch, false);
                                            tv.setText(keyword);
                                            tv.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    TextView tv= (TextView) v;
                                                    String key = tv.getText().toString().trim();
                                                    Intent intent=new Intent(MainActivity2.this,ProductListShowActivity.class);
                                                    Bundle bundle=new Bundle();
                                                    bundle.putString("key","search");
                                                    bundle.putString("keyword",key);
                                                    intent.putExtras(bundle);
                                                    startActivity(intent);
                                                }
                                            });
                                            mHotSearch.addView(tv);
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            CommonUtil.showToast(MainActivity2.this, "请求失败:错误码为" + statusCode);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(MainActivity2.this, "网络未连接" + msg);
                    }
                });
    }

    /**
     * 清除搜索历史
     * 作者:孙建
     * created at 2016/4/21 8:26
     */
    public void clearSearchHistory(View view) {
        SearchHistoryInfoDBUtil.clearAllSearchHistoryInfo();
        setSearchHistoryInfoAdapter();
    }

    /**
     * 菜单
     * 作者:孙建
     * created at 2016/4/21 16:54
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        initListView();
        initSearchView(menu);
        settingsItem = menu.findItem(R.id.action_add_friend);
        //  settingsItem.setIcon(R.drawable.ic_menu_moreoverflow_normal_holo_light);
        settingsItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (isVoice) {
                   // CommonUtil.showSingleToast(MainActivity2.this, "我是语音");
                    showReconigizerDialog();
                } else {
                    if (mIsBrand) {
                        CommonUtil.showSingleToast(MainActivity2.this, "我是筛选");
                    } else if (mIsCart) {
                        //   CommonUtil.showSingleToast(MainActivity2.this, "我是购物车");
                        ((CartFragment) (mFragments.get(2))).cartEdit();
                    } else {
                        int itemId = settingsItem.getItemId();
                        View viewById = findViewById(itemId);
                        initPopupWindow(viewById);
                    }
                }
                return false;
            }
        });
        return true;
    }

    /**
     * 初始化pw
     * 作者:孙建
     * created at 2016/4/21 16:54
     */
    private void initPopupWindow(View view) {
        View pwView = View.inflate(this, R.layout.view_popupwindow_index, null);
        View pwTop = pwView.findViewById(R.id.ll_pw_top);
        View pwBottom = pwView.findViewById(R.id.ll_pw_bottom);
        mPopupWindow = new PopupWindow(pwView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        mPopupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
        int[] location = new int[2];
        view.getLocationInWindow(location);
        mPopupWindow.showAsDropDown(view, (int) -CommonUtil.dpToPx(this, 80), (int) -CommonUtil.dpToPx(this, 10));
        pwTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity2.this, MessageActivity.class);
                startActivity(intent);
                mPopupWindow.dismiss();
            }
        });
        pwBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity2.this, CaptureActivity.class);
                startActivityForResult(intent,0);
                mPopupWindow.dismiss();
            }
        });
        //  popupWindow.showAtLocation(view, Gravity.RIGHT| Gravity.TOP, location[0]+40, location[1] + 40);
    }

    /**
     * 初始化搜索提示listview
     * 作者:孙建
     * created at 2016/4/21 16:55
     */
    private void initListView() {
        if (mAdapter == null) {
            List<String> infos = new ArrayList<>();
            for (int i = 0; i < Cheeses.SEARCH_TIPS.length; i++) {
                infos.add(Cheeses.SEARCH_TIPS[i]);
            }
            //    mSearchList.setEmptyView(findViewById(R.id.ll_search_empty));
            mAdapter = new SearchAdapter(this, infos);
            mSearchList.setAdapter(mAdapter);
            mSearchList.setTextFilterEnabled(true);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        mSearchList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SearchAdapter adapter = (SearchAdapter) parent.getAdapter();
                String key = adapter.getItem(position);
                // SearchHistoryInfoDBUtil.saveSearchHistoryInfo(new SearchHistoryInfo(key));
                SearchInfo searchInfo = new SearchInfo();
                searchInfo.setKeyword(key);
                searchInfo.setPage(CommonConstant.DEFAULT_PAGE);
                searchInfo.setPageNum(CommonConstant.DEFAULT_PAGE_NUM);
                /*Intent intent=new Intent(MainActivity2.this,SearchResultActivity.class);
                intent.putExtra("keyword",key);
                startActivity(intent);*/
                initNeedSearchInfo(searchInfo);
            }
        });
    }

    /**
     * 初始化toolbar
     * 作者:孙建
     * created at 2016/4/21 16:55
     */
    private void initToolbar() {
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        //  mToolbar.setMenu();
    }

    public Toolbar getToolbar() {
        return mToolbar;
    }

    /**
     * 初始化搜索view的相关数据和事件
     * 作者:孙建
     * created at 2016/4/21 14:59
     */
    private void initSearchView(Menu menu) {
        mSearch = menu.findItem(R.id.menu_search);
       /* search.collapseActionView();
        search.expandActionView();*/
        mSearchView = (SearchView) mSearch.getActionView();
        mSearchView.setIconifiedByDefault(true);
        //   mSearchView.setSubmitButtonEnabled(true);
        mSearchView.setQueryHint("搜索");
        MenuItemCompat.setOnActionExpandListener(mSearch, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                isVoice = false;
                if (mIsBrand) {
                    settingsItem.setIcon(R.drawable.ic_drawer);
                } else if (mIsCart) {
                    settingsItem.setIcon(R.drawable.cart_edit);
                } else {
                    settingsItem.setIcon(R.drawable.ic_menu_moreoverflow_normal_holo_light);
                }
                mLLShowMsg.setVisibility(View.VISIBLE);
                mRLSearchMsg.setVisibility(View.GONE);
                return true;
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                initHistoryData();
                isVoice = true;
                settingsItem.setIcon(R.drawable.ic_btn_speak_now);
                mLLShowMsg.setVisibility(View.GONE);
                mRLSearchMsg.setVisibility(View.VISIBLE);
                return true;
            }
        });
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                /*if(TextUtils.isEmpty(query)){
                    Log.d("test","搜索空的");
                    CommonUtil.showToast(MainActivity2.this,"请输入你想要的商品");
                    return true;
                }*/
                Log.d("test", "query" + query);
                SearchInfo searchInfo = new SearchInfo();
                searchInfo.setKeyword(query);
                searchInfo.setPage(CommonConstant.DEFAULT_PAGE);
                searchInfo.setPageNum(CommonConstant.DEFAULT_PAGE_NUM);
                /*Intent intent=new Intent(MainActivity2.this,SearchResultActivity.class);
                intent.putExtra("keyword",query);
                startActivity(intent);*/
                initNeedSearchInfo(searchInfo);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (mAdapter instanceof Filterable) {
                    Filter filter = mAdapter.getFilter();
                    if (TextUtils.isEmpty(newText)) {
                        filter.filter(null);
                        mSearchList.setVisibility(View.INVISIBLE);
                        mSearchEmpty.setVisibility(View.VISIBLE);
                    } else {
                        mSearchEmpty.setVisibility(View.INVISIBLE);
                        mSearchList.setVisibility(View.VISIBLE);
                        filter.filter(newText);
                    }
                }
                return true;
            }
        });
    }

    /**
     * 初始化头部
     * 作者:孙建
     * created at 2016/4/21 16:55
     */
    private void initHead() {
        mMainIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initLeftMenuOpenStatus(true);
               /* Intent intent=new Intent(MainActivity2.this,UserDetailsActivity.class);
                intent.putExtra("index",2);
                startActivity(intent);*/
            }
        });
        /*mSearchImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity2.this, SearchActivity.class);
                startActivity(intent);
            }
        });*/
    }

    /**
     * 初始化侧滑菜单
     * 作者:孙建
     * created at 2016/4/21 16:55
     */
    private void initLeftMenuOpenStatus(boolean isOpposite) {
        if (isOpposite) {
            if (mMySlidingMenu.getStatus() == DragLayout.Status.Close) {
                mMySlidingMenu.open();
            } else {
                mMySlidingMenu.close();
            }
        } else {
            if (mMySlidingMenu.getStatus() != DragLayout.Status.Close) {
                mMySlidingMenu.close();
            }
        }
    }


    private void init() {
        initFragment();
        initMain();
        initLeftMenu();
    }

    /**
     * 显示的时候需要更新的东西
     * 作者:孙建
     * created at 2016/4/21 16:56
     */
    @Override
    protected void onResume() {
        super.onResume();
        initLeftMenuOpenStatus(false);
        setLeftMenuImg(isLogin, mUserInfo);
    }

    private List<ChangeColorIconWithText> mTabIndicators = new ArrayList<ChangeColorIconWithText>();

    /**
     * 初始化指示器
     * 作者:孙建
     * created at 2016/4/21 16:56
     */
    private void initBottomView() {
        ChangeColorIconWithText one = (ChangeColorIconWithText) findViewById(R.id.id_indicator_one);
        mTabIndicators.add(one);
        ChangeColorIconWithText two = (ChangeColorIconWithText) findViewById(R.id.id_indicator_two);
        mTabIndicators.add(two);
        ChangeColorIconWithText three = (ChangeColorIconWithText) findViewById(R.id.id_indicator_three);
        mTabIndicators.add(three);
        ChangeColorIconWithText four = (ChangeColorIconWithText) findViewById(R.id.id_indicator_four);
        mTabIndicators.add(four);
        one.setOnClickListener(this);
        two.setOnClickListener(this);
        three.setOnClickListener(this);
        four.setOnClickListener(this);
        one.setIconAlpha(1.0f);
    }

    private void initMain() {
        initBottomView();
       /* mainViewIndex.setOnMenuStatusChangeListener(new MainContenLinearLayout.OnMenuStatusChangeListener() {
            @Override
            public boolean isOpen() {
                if (mMySlidingMenu.getStatus()!= DragLayout.Status.Close) {
                    return true;
                }
                return false;
            }
            @Override
            public void close() {
                mMySlidingMenu.close();
            }
        });*/
        initViewPager();
    }

    /**
     * 初始化vp
     * 作者:孙建
     * created at 2016/4/21 16:56
     */
    private void initViewPager() {

        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments == null ? 0 : mFragments.size();
            }
        });
        onPageSelected(0);
        mViewPager.addOnPageChangeListener(this);
    }

    /**
     * 初始化菜单
     * 作者:孙建
     * created at 2016/4/21 16:57
     */
    private void initLeftMenu() {
        initLeftMenuData();
        mImgLeftHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin) {
                    Intent intent = new Intent(MainActivity2.this, UserDetailsActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(MainActivity2.this, LoginAndRegisterActivity.class);
                    startActivityForResult(intent, CommonUtil.LOGIN_AND_REGISTER_REQUEST_CODE);
                }
            }
        });
        setLeftMenuAdapter();
        /*mListViewMain.setAdapter(mLeftAdapter = new ArrayAdapter<LeftMenuItem>(this,
                android.R.layout.simple_list_item_1,
                mLeftMenuItems));*/
        mLeftMenuListView.setOnItemClickListener(this);
        mMySlidingMenu.setDragListener(new DragLayout.DragListener() {
            @Override
            public void onOpen() {

            }

            @Override
            public void onClose() {
                ObjectAnimator ta = ObjectAnimator.ofFloat(mMainIcon, "translationX", 5.0f);
                ta.setDuration(500);
                ta.setInterpolator(new CycleInterpolator(5.0f));
                ta.start();
            }

            @Override
            public void onDrag(float percent) {
                ViewCompat.setAlpha(mMainIcon, 1 - percent);
            }
        });
        /*mMySlidingMenu.setOnSlidingMenuStatusChangeListener(new MySlidingMenu.OnSlidingMenuStatusChangeListener() {
            @Override
            public void open() {

            }

            @Override
            public void close() {
                ObjectAnimator ta = ObjectAnimator.ofFloat(mMainIcon, "translationX", 5.0f);
                ta.setDuration(500);
                ta.setInterpolator(new CycleInterpolator(5.0f));
                ta.start();
            }

            @Override
            public void drag(float percent) {
                ViewCompat.setAlpha(mMainIcon, 1 - percent);
            }
        });*/
        mMySlidingMenu.setOnSlidingMenuScrollListener(new DragLayout.OnSlidingMenuScrollListener() {
            @Override
            public boolean isScroll() {
                //   CommonUtil.showSingleToast(MainActivity2.this,"isVoice"+isVoice);
                if (!isVoice) {
                    if (scrollIndex != 0) {
                        return false;
                    }
                    return true;
                }
                return false;
            }
        });
    }

    private void setLeftMenuImg(boolean isLogin, UserInfo userInfo) {
        Bitmap initHeadDefaultImage = BitmapFactory.decodeResource(getResources(), R.drawable.inithead);
        if (isLogin) {
            Bitmap headImage = BitmapFactory.decodeFile(CommonUtil.USER_HEAD_IMAGE_PATH);
            Bitmap headDefaultImage = BitmapFactory.decodeResource(getResources(), R.drawable.head);
            UserInfo myUserInfo = UserInfoDBUtil.queryUserInfoByUserId(SPUtil.getString(this, SPConstant.USER_INFO_USER_ID));
            if (headImage == null) {
                mImgLeftHead.setImageBitmap(headDefaultImage);
                if (myUserInfo != null) {
                    if (!TextUtils.isEmpty(myUserInfo.getNickname())) {
                        mAccountName.setText(myUserInfo.getNickname());
                    } else {
                        mAccountName.setText(userInfo.getUsername());
                    }
                }
                mMainIcon.setImageBitmap(headDefaultImage);
                return;
            }
            // mImgLeftHead.setImageResource(R.drawable.head);
            mImgLeftHead.setImageBitmap(headImage);
            if (myUserInfo != null) {
                if (!TextUtils.isEmpty(myUserInfo.getNickname())) {
                    mAccountName.setText(myUserInfo.getNickname());
                } else {
                    mAccountName.setText(userInfo.getUsername());
                }
            }
            mMainIcon.setImageBitmap(headImage);
            // mMainIcon.setImageResource(R.drawable.head);
            return;
        }
        mImgLeftHead.setImageBitmap(initHeadDefaultImage);
        mMainIcon.setImageBitmap(initHeadDefaultImage);
        mAccountName.setText("");

    }

    private void setLeftMenuAdapter() {
        if (mLeftMenuItemAdapter == null) {
            mLeftMenuItemAdapter = new LeftMenuItemAdapter(this, mLeftMenuItems);
            mLeftMenuListView.setAdapter(mLeftMenuItemAdapter);
        } else {
            mLeftMenuItemAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 初始化左边菜单数据
     * 作者:孙建
     * created at 2016/4/21 16:57
     */
    private void initLeftMenuData() {
        mLeftMenuItems.add(new LeftMenuItem(R.drawable.my_indent, "全部订单"));
        mLeftMenuItems.add(new LeftMenuItem(R.drawable.my_collect, "我的收藏"));
        mLeftMenuItems.add(new LeftMenuItem(R.drawable.my_client_service, "联系客服"));
        mLeftMenuItems.add(new LeftMenuItem(R.drawable.my_favorable, "我的优惠券"));
        mLeftMenuItems.add(new LeftMenuItem(R.drawable.my_login_back, "退出"));
    }
/**
 * 回调的时候记得处理下面指示器
 * 作者:孙建
 * created at 2016/4/25 16:03
 */
    private void initFragment() {
        mFragments.add(new HomeFragment());
        mFragments.add(new CategoryFragment());
        CartFragment cartFragment = new CartFragment();
        cartFragment.setOnUserDetailsClickListener(new BaseFragment.OnUserDetailsClickListener() {
            @Override
            public void onClick(int index) {
                resetOtherTabs();
                mTabIndicators.get(index).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(index,false);
            }
        });
        mFragments.add(cartFragment);
        mFragments.add(new FourFragment());
    }

    /**
     * 处理左边菜单条目点击事件
     * 作者:孙建
     * created at 2016/4/21 16:58
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = null;
        int headerViewsCount = mLeftMenuListView.getHeaderViewsCount();
        position = position - headerViewsCount;
        switch (position) {
            case 0:
                /*intent = new Intent(this, IndentActivity.class);
                startActivity(intent);*/
                int[] location = new int[2];
                view.getLocationInWindow(location);
                mWm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                WindowManager.LayoutParams params = new WindowManager.LayoutParams();
                params.height = WindowManager.LayoutParams.WRAP_CONTENT;
                params.width = WindowManager.LayoutParams.WRAP_CONTENT;
                params.format = PixelFormat.TRANSLUCENT;
                final RollMenuView menuView = new RollMenuView(this);
                menuView.setInitLoaction(location[0] + 200, location[1] + 530);
                menuView.setOnRollMenuViewListener(new RollMenuView.OnRollMenuViewListener() {
                    @Override
                    public void finish() {
                        ObjectAnimator anim = ObjectAnimator
                                .ofFloat(menuView, "sunjian", 1.0F, 0.0F)
                                .setDuration(1000);
                        anim.start();
                        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {
                                float cVal = (Float) animation.getAnimatedValue();
                                menuView.setAlpha(cVal);
                                menuView.setScaleX(cVal);
                                menuView.setScaleY(cVal);
                            }
                        });
                        anim.addListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (menuView != null) {
                                    mWm.removeView(menuView);
                                }
                            }
                        });
                    }
                });
                menuView.setOnRollClickListener(new RollMenuView.OnRollClickListener() {
                    @Override
                    public void onRollClick(int index) {
                     //   CommonUtil.showToast(MainActivity2.this,"index"+index);
                        if(index<4){
                            Intent intent=new Intent(MainActivity2.this,IndentActivity.class);
                            intent.putExtra("indentIndex",index);
                            startActivity(intent);
                        }else {
                            Intent intent=new Intent(MainActivity2.this,UserAgainstActivity.class);
                            startActivity(intent);
                        }
                        if (menuView != null) {
                            mWm.removeView(menuView);
                        }
                    }
                });
                mWm.addView(menuView, params);
                menuView.startAnim();
                break;
            case 1:
                intent = new Intent(this, CollectActivity.class);
                startActivity(intent);
                break;
            case 2:
                intent = new Intent(this, UserServiceActivity.class);
                startActivity(intent);
                break;
            case 3:
                break;
            case 4:
                if (isLogin) {
                    logout();
                }
                break;
        }
    }

    /**
     * 登出处理
     * 作者:孙建
     * created at 2016/4/21 19:06
     */
    public void logout() {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        RequestParams params = new RequestParams();
        params.addHeader("userid", SPUtil.getString(this, SPConstant.USER_INFO_USER_ID));
        mHttpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST_LOGOUT, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if (response.equals("logout")) {
                                    isLogin = false;
                                    SPUtil.put(MainActivity2.this, SPConstant.USER_INFO_IS_LOGIN, false);
                                    SPUtil.put(MainActivity2.this, SPConstant.USER_INFO_USER_ID, "");
                                    Bitmap headDefaultImage = BitmapFactory.decodeResource(getResources(), R.drawable.inithead);
                                    mImgLeftHead.setImageBitmap(headDefaultImage);
                                    mAccountName.setText("");
                                    mUserInfo = null;
                                    mMainIcon.setImageBitmap(headDefaultImage);
                                    CommonUtil.showToast(MainActivity2.this, "登出成功");
                                } else {
                                    String error = jsonObject.getString("error");
                                    String error_code = jsonObject.getString(CommonConstant.ERROR_CODE);
                                    if (error_code.equals(CommonConstant.ERROR_CODE_NO_USERID_ON_REQUEST_HEAD)) {
                                        CommonUtil.showToast(MainActivity2.this, error);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            CommonUtil.showToast(MainActivity2.this, "请求失败:错误码为" + statusCode);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(MainActivity2.this, "网络未连接" + msg);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        clickTab(v);
    }

    private void resetOtherTabs() {
        for (int i = 0; i < mTabIndicators.size(); i++) {
            mTabIndicators.get(i).setIconAlpha(0);
        }
    }

    /**
     * 处理点击指示器的事件
     * 作者:孙建
     * created at 2016/4/21 16:58
     */
    private void clickTab(View v) {
        resetOtherTabs();

        switch (v.getId()) {
            case R.id.id_indicator_one:
                mTabIndicators.get(0).setIconAlpha(1.0f);
                // mViewPager.setCurrentItem(0);
                mViewPager.setCurrentItem(0, false);
                break;
            case R.id.id_indicator_two:
                mTabIndicators.get(1).setIconAlpha(1.0f);
                //  mViewPager.setCurrentItem(1);
                mViewPager.setCurrentItem(1, false);
                break;
            case R.id.id_indicator_three:
                mTabIndicators.get(2).setIconAlpha(1.0f);
                // mViewPager.setCurrentItem(2);
                mViewPager.setCurrentItem(2, false);
                break;
            case R.id.id_indicator_four:
                mTabIndicators.get(3).setIconAlpha(1.0f);
                //  mViewPager.setCurrentItem(3);
                mViewPager.setCurrentItem(3, false);
                break;
        }
    }

    /**
     * 指示器滑动处理事件
     * 作者:孙建
     * created at 2016/4/21 16:58
     */
    @Override
    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {
        if (positionOffset > 0) {
            ChangeColorIconWithText left = mTabIndicators.get(position);
            ChangeColorIconWithText right = mTabIndicators.get(position + 1);
            left.setIconAlpha(1 - positionOffset);
            right.setIconAlpha(positionOffset);
        }
        ViewCompat.setRotationY(mMainIcon,positionOffset*360f);
        ViewCompat.postInvalidateOnAnimation(mMainIcon);
    }
/**
 * vp滑动处理
 * 作者:孙建
 * created at 2016/4/25 15:58
 */
    @Override
    public void onPageSelected(int position) {
        if (position == 1) {
            mIsBrand = true;
            mIsCart = false;
            if (settingsItem != null) {
                settingsItem.setIcon(R.drawable.ic_drawer);
            }
        } else if (position == 2) {
            mIsBrand = false;
            mIsCart = true;
            if (settingsItem != null) {
                settingsItem.setIcon(R.drawable.cart_edit);
            }
        } else {
            mIsCart = false;
            mIsBrand = false;
            if (settingsItem != null) {
                settingsItem.setIcon(R.drawable.ic_menu_moreoverflow_normal_holo_light);
            }
        }
        this.scrollIndex = position;
        mMainTitle.setText(mTabIndicators.get(position).getText());
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * activity回调处理
     * 作者:孙建
     * created at 2016/4/21 16:59
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CommonUtil.LOGIN_AND_REGISTER_REQUEST_CODE && resultCode == CommonUtil.LOGIN_AND_REGISTER_REGISTER_RESULT_CODE) {
            UserInfo userInfo = data.getParcelableExtra("UserInfo");
            if (userInfo != null) {
                mUserInfo = userInfo;
                disposeUserInfo(userInfo.getUserid());
                isLogin = true;
                setLeftMenuImg(isLogin, mUserInfo);
                initLeftMenuOpenStatus(false);
            }
        } else if (requestCode == CommonUtil.LOGIN_AND_REGISTER_REQUEST_CODE && resultCode == CommonUtil.LOGIN_AND_REGISTER_LOGIN_RESULT_CODE) {
            UserInfo userInfo = data.getParcelableExtra("UserInfo");
            if (userInfo != null) {
                mUserInfo = userInfo;
                disposeUserInfo(userInfo.getUserid());
                //    Log.d("test", "Mainlogin" + mUserInfo.toString());
                isLogin = true;
                setLeftMenuImg(isLogin, mUserInfo);
            }
        }else if(requestCode==0&&resultCode==RESULT_OK){
            String result = data.getExtras().getString("result");
            /*new AlertDialog.Builder(this)
                    .setTitle("二维码扫描结果")
                    .setMessage(result)
                    .show();*/
            Intent intent=new Intent(MainActivity2.this,ProductListShowActivity.class);
            Bundle bundle=new Bundle();
            bundle.putString("key","search");
            bundle.putString("keyword",result);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        logout();
        BusFactory.getBus().unregister(this);
    }

    @Subscribe
    public void changeNickName(UserInfo userInfo) {
        Log.d("test", "wooo" + userInfo.getNickname());
        mAccountName.setText(userInfo.getNickname());
    }

    /**
     * 处理搜索切换
     * 作者:孙建
     * created at 2016/4/21 16:59
     */
    @Override
    public void onBackPressed() {
        if (isVoice) {
            isVoice = false;
            settingsItem.setIcon(R.drawable.ic_menu_moreoverflow_normal_holo_light);
            mLLShowMsg.setVisibility(View.VISIBLE);
            mRLSearchMsg.setVisibility(View.GONE);
            MenuItemCompat.collapseActionView(mSearch);
            return;
        }
        super.onBackPressed();
    }

    /**
     * 请求用户信息
     * 作者:孙建
     * created at 2016/4/21 20:13
     */
    private void disposeUserInfo(String userid) {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        RequestParams params = new RequestParams();
        params.addHeader("userid", userid);
        mHttpUtils.send(HttpRequest.HttpMethod.POST, CommonConstant.HOST_USER_INFO, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if (response.equals("userInfo")) {
                                    String userInfoStr = jsonObject.getString("userInfo");
                                    UserInfo userInfo = mGson.fromJson(userInfoStr, UserInfo.class);
                                    if (userInfo.getLevel().equals("白银会员")) {
                                        mMainIcon.setBorderColor(Color.GREEN);
                                        mImgLeftHead.setBorderColor(Color.GREEN);
                                    } else if (userInfo.getLevel().equals("白金会员")) {
                                        mMainIcon.setBorderColor(Color.BLUE);
                                        mImgLeftHead.setBorderColor(Color.BLUE);
                                    } else if (userInfo.getLevel().equals("铂金会员")) {
                                        mMainIcon.setBorderColor(Color.RED);
                                        mImgLeftHead.setBorderColor(Color.RED);
                                    } else if (userInfo.getLevel().equals("普通会员")) {
                                        mMainIcon.setBorderColor(Color.WHITE);
                                        mImgLeftHead.setBorderColor(Color.WHITE);
                                    }
                                    UserInfoDBUtil.updateUserInfo(userInfo);
                                } else {
                                    String error = jsonObject.getString("error");
                                    String error_code = jsonObject.getString(CommonConstant.ERROR_CODE);
                                    if (error_code.equals(CommonConstant.ERROR_CODE_NO_USERID_ON_REQUEST_HEAD)) {
                                        CommonUtil.showToast(MainActivity2.this, error);
                                    } else if (error_code.equals(CommonConstant.ERROR_CODE_UNLOGIN)) {
                                        CommonUtil.showToast(MainActivity2.this, error);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            CommonUtil.showToast(MainActivity2.this, "请求失败:错误码为" + statusCode);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(MainActivity2.this, "网络未连接" + msg);
                    }
                });
    }

    private boolean mIsNight;

    public void night(View view) {
        if (mIsNight) {
            mIsNight = false;
            mMySlidingMenu.setBackgroundResource(R.drawable.my_menu_bg);
        } else {
            mIsNight = true;
            mMySlidingMenu.setBackgroundResource(R.drawable.bg);
        }
    }
    private void showReconigizerDialog() {
        //setEngine(String engine,String params,String grammar);
        rd.setEngine("sms", null, null);
        //设置采样频率，默认是16k，android手机一般只支持8k、16k.为了更好的识别，直接弄成16k即可。
        rd.setSampleRate(SpeechConfig.RATE.rate16k);
        final StringBuilder sb = new StringBuilder();
        Log.i("test", "识别准备开始.............");
        //设置识别后的回调结果
        rd.setListener(new RecognizerDialogListener() {
            @Override
            public void onResults(ArrayList<RecognizerResult> result, boolean isLast) {
                for (RecognizerResult recognizerResult : result) {
                    sb.append(recognizerResult.text);
                    Log.i("test", "识别一条结果为::"+recognizerResult.text);
                }
            }
            @Override
            public void onEnd(SpeechError error) {
                Intent intent=new Intent(MainActivity2.this,ProductListShowActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("key","search");
                sb.deleteCharAt(sb.length()-1);
                bundle.putString("keyword",sb.toString());
                intent.putExtras(bundle);
                startActivity(intent);
               // CommonUtil.showToast(MainActivity2.this,sb.toString());
            }
        });

        rd.show();
    }
}
